34D - Road Map - CodeForces Solution


dfs and similar graphs *1600

Please click on ads to support us..

Python Code:

n,r1,r2=map(int,input().split())

P=list(map(int,input().split()))

E=[[] for i in range(n+1)]

x=1
for i in range(n-1):
    if x==r1:
        x+=1
    p=P[i]
    E[x].append(p)
    E[p].append(x)

    x+=1


P2=[-1]*(n+1)

Q=[r2]

while Q:
    x=Q.pop()
    for to in E[x]:
        if P2[to]==-1:
            P2[to]=x
            Q.append(to)

ANS=P2[1:r2]+P2[r2+1:n+1]
print(*ANS)

C++ Code:

#include <iostream>
#include <vector>
#include <stack>
#include <string>
#include <utility>
#include <queue>
#include <iomanip>
#include <set>
#include <map>
#include <cmath>
#include <algorithm>
#include <unordered_map>
#include <unordered_set>
using namespace std;
#define vi vector<int>
#define ll long long

const int N = 5e4 + 5;
vector<int> v[N];
int ans[N];

void dfs(int n) {
	for (auto& a : v[n]) {
		if (a == ans[n])
			continue;

		ans[a] = n;
		dfs(a);
	}
}


int main() {
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);

	int n, r1, r2;
	cin >> n >> r1 >> r2;
	
	for (int i = 1; i <= n; ++i) {
		if (i == r1)
			continue;

		int x;
		cin >> x;
		v[i].push_back(x);
		v[x].push_back(i);
	}
	
	dfs(r2);
	for (int i = 1; i <= n; ++i) {
		if (i == r2)
			continue;

		cout << ans[i] << ' ';
	}

	return 0;
}
	  	  	  			 	 		  		    	 			


Comments

Submit
0 Comments
More Questions

1702C - Train and Queries
816B - Karen and Coffee
838D - Airplane Arrangements
148B - Escape
847G - University Classes
1110A - Parity
1215B - The Number of Products
604C - Alternative Thinking
1204C - Anna Svyatoslav and Maps
322A - Ciel and Dancing
1689B - Mystic Permutation
1711B - Party
1702D - Not a Cheap String
1714F - Build a Tree and That Is It
1703F - Yet Another Problem About Pairs Satisfying an Inequality
610A - Pasha and Stick
1200A - Hotelier
1091A - New Year and the Christmas Ornament
1352B - Same Parity Summands
1102A - Integer Sequence Dividing
630B - Moore's Law
1004A - Sonya and Hotels
1680B - Robots
1690A - Print a Pedestal (Codeforces logo)
1295A - Display The Number
1077A - Frog Jumping
1714G - Path Prefixes
1369C - RationalLee
289B - Polo the Penguin and Matrix
1716A - 2-3 Moves